package manager;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;
import utils.LockUtil;

/**
 * Servlet implementation class RemoveCourseUser
 */
public class RemoveCourseUser extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
       
   

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
		
		response.setContentType("text/html");
		boolean isAdmin = request.getSession(false).getAttribute("type").toString().equals("admin");
		String username = null;
		if (isAdmin){
			username = request.getParameter("username");
		}
		else{
			username = request.getSession(false).getAttribute("username").toString();
		}
		
		
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
						"DELETE from user_courses " +
						"where course_name=? and username=? ; ");
	
			stmnt.setString(2, username);
			
				
			String[] names = request.getParameterValues("check");
			if (names == null){
				response.sendRedirect("/");
			}
			
			synchronized (LockUtil.getUserCoursesLock()) {
				for (String name : names){
					stmnt.setString(1, name);
					stmnt.execute();
				}
			}
			
			String returnLink = request.getSession(false).getAttribute("type").toString().equals("admin") ? "manage_courses.jsp" : "user_manage_courses.jsp";
			response.sendRedirect(returnLink);
		
		
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Error");
			return;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Error");
			return;
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
